//
//  NetController.m
//  test
//
//  Created by 科迈捷 on 2017/4/12.
//  Copyright © 2017年 科迈捷. All rights reserved.
//

#import "NetController.h"
#import <pthread.h>

@interface NetController (){
    NSArray *_titles;
    UIImage *_image;
}

@end

@implementation NetController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"网络及多线程";
    _titles = @[@"synchronized",@"NSLock",@"GCD",@"pthread",@"NSThread",@"切换主线程"];
    self.view.layer.contentsGravity = @"resizeAspectFill";
    self.view.layer.masksToBounds = YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = _titles[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
            [self testSynchronized];
            break;
        case 1:
            [self testNSLock];
            break;
        case 2:
            [self testGCD];
            break;
        case 3:
            [self testPthreads];
            break;
        case 4:
            [self testNSThread];
            break;
        case 5:
            [self goToMainThread];
        break;
        default:
            break;
    }
}

#pragma mark - 线程安全
- (void)testSynchronized {
    Animal *someone = [Animal new];
    //线程A
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        @synchronized (someone) {
            NSLog(@"线程A=%@",[NSThread currentThread]);
            someone.name = @"🕊";
            [NSThread sleepForTimeInterval:5];
        }
    });
    
    //线程B
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        @synchronized (someone) {
            NSLog(@"线程B=%@",[NSThread currentThread]);
            someone.name = @"🐰";
        }
    });
}

- (void)testNSLock {
    Animal *someone = [Animal new];
    //创建锁对象
    NSLock *alock = [[NSLock alloc]init];
    //线程A
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //锁
        //尝试上锁
        if ([alock tryLock]) {
//                [alock lock];
            NSLog(@"线程A=%@",[NSThread currentThread]);
            someone.name = @"🕊";
            [NSThread sleepForTimeInterval:5];
            //开锁
            [alock unlock];
        }
        
    });
    
    //线程B
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([alock tryLock]) {
//                [alock lock];
            NSLog(@"线程B=%@",[NSThread currentThread]);
            someone.name = @"🐰";
            [alock unlock];
        }
    });
}

- (void)testGCD {
    Animal *someone = [Animal new];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    //线程A
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //等待，如果信号大于0，则继续并减少一个信号
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"线程A=%@",[NSThread currentThread]);
        someone.name = @"🕊";
        [NSThread sleepForTimeInterval:5];
        //信号加1
        dispatch_semaphore_signal(semaphore);
    });
    
    //线程B
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"线程B=%@",[NSThread currentThread]);
        someone.name = @"🐰";
        dispatch_semaphore_signal(semaphore);
    });
}
    
- (void)testPthreads {
    //创建一个线程并自动执行start方法
    pthread_t thread;
    pthread_create(&thread, NULL, start, NULL);
}
    void *start(void *data) {
        NSLog(@"当前线程 = %@",[NSThread currentThread]);
        return NULL;
    }
    
- (void)testNSThread {
    //1 创建一个新线程
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:nil];
    //启动线程
    [thread start];
    /*2 创建后直接启动
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:nil];*/
    /*3 隐式创建
     [self performSelectorInBackground:@selector(run:) withObject:nil];
     */
    
}
    
- (void)run:(NSThread *)thread {
    for (int i = 0; i < 10; i++) {
        NSLog(@"%zd",i);
    }
    //取消线程
    [thread cancel];
}
    
- (void)goToMainThread {
    //开启子线程 下载图片
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://distribute.quanjing.com/pe0060886.jpg?seid=CguWmdyWodG2Fg9QBZaWmxWXmNX8FhX8mZaWFdiWmtCVnc8XnYaXntO1otOWmNWWFa%3d%3dac2ad5aa50b5237cbe7078e75c0c0b44"]];
        _image = [UIImage imageWithData:imageData];
        //切换到主线程显示
//        [self performSelectorOnMainThread:@selector(changeBg) withObject:nil waitUntilDone:NO];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self changeBg];
//        });
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [self changeBg];
        }];
    });
}
         
- (void)changeBg {
    self.view.layer.contents = (id)_image.CGImage;
}

@end
